package com.fly.lambda.framework.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Fly on 2016/7/19.
 */
public class CookieUtil {

    public static void writeCookie(HttpServletResponse response, String name, String value){
        writeCookie(response, name, value, "/", Integer.MAX_VALUE);
    }

    public static void writeCookie(HttpServletResponse response, String name, String value, String path , int maxAge){
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setPath(path);

        response.addCookie(cookie);
    }

    public static String readCookie(HttpServletRequest request, String name){
        String value = "";
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if (cookie.getName().equals(name)){
                value = cookie.getValue();
                break;
            }
        }
        return value;
    }

    public static void removeCookie(HttpServletResponse response,String name){
        writeCookie(response, name, null, "/", 0);
    }
}
